package com.siyoumi.app.modules.redbook.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.RedbookComment;
import com.siyoumi.app.entity.RedbookQuan;
import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.modules.redbook.service.SvcRedbookComment;
import com.siyoumi.app.modules.redbook.service.SvcRedbookQuan;
import com.siyoumi.app.modules.redbook.vo.RedbookCommentVo;
import com.siyoumi.app.modules.redbook.vo.VoRedbookCommentDel;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/wxapp/redbook/api_comment")
public class ApiRedbookComment
        extends WxAppApiController {
    /**
     * 是否评论
     */
    @GetMapping({"send_can"})
    public XReturn commentSendCan() {
        XReturn r = XReturn.getR(0);
        r.setData("can_comment", true);
        return r;
    }

    /**
     * 发朋友圈
     */
    @PostMapping({"send"})
    public XReturn commentSend(@Validated RedbookCommentVo vo, BindingResult result) {
        //通用验证
        XValidator.getResult(result, true, true);

        XReturn r = SvcRedbookComment.getBean().commentQuan(vo);
        if (r.err()) {
            return r;
        }

        RedbookComment entity = r.getData("entity");
        //
        //统一输出
        JoinWrapperPlus<RedbookComment> query = SvcRedbookComment.getBean().selectQuery(InputData.getIns());
        query.eq("rbc_id", entity.getRbc_id());
        Map<String, Object> mapComment = SvcRedbookComment.getApp().firstMap(query);
        //mapComment.put("is_good", false);
        mapComment.put("list_2", new ArrayList<>());

        r.setData("entity", mapComment);
        return r;
    }

    protected Integer getCommentMaxNum() {
        return 3;
    }

    /**
     * 评论列表
     */
    @GetMapping({"list"})
    public XReturn commentList() {
        InputData inputData = InputData.fromRequest();
        String quanId = input("quan_id");
        if (XStr.isNullOrEmpty(quanId)) {
            return EnumSys.MISS_VAL.getR("miss quan_id");
        }

        JoinWrapperPlus<RedbookComment> query = SvcRedbookComment.getBean().selectQuery(inputData);
        query.eq("rbc_pid", "")
                .eq("rbc_enable", 1)
        //.eq("rbc_is_master", 0)
        ;
        query.orderByDesc("rbc_create_date")
                .orderByAsc("rbc_id");
        IPage<RedbookComment> page = new Page<>(getPageIndex(), getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcRedbookComment.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();

        List<String> pidArr = list.stream().filter(item -> {
            return XStr.hasAnyText((String) item.get("rbc_id"));
        }).map(item -> (String) item.get("rbc_id")).collect(Collectors.toList());
        List<Map<String, Object>> listComment2 = new ArrayList<>();
        if (pidArr.size() > 0) {
            //2级评论
            JoinWrapperPlus<RedbookComment> queryList2 = SvcRedbookComment.getBean().selectQuery(pidArr);
            queryList2.le("rbc_reply_num", getCommentMaxNum())
                    .orderByAsc("rbc_create_date")
                    .orderByAsc("rbc_id");
            listComment2 = SvcRedbookComment.getApp().getMaps(queryList2);
        }

        for (Map<String, Object> item : list) {
            RedbookComment entityComment = SvcRedbookComment.getApp().loadEntity(item);
            //是否点赞
            //boolean doGood = SvcRedbookData.getBean().existsEntity("comment", entityComment.getRbc_id(), getUid());
            //item.put("is_good", doGood);

            //2级评论，处理
            List<Map<String, Object>> list2 = listComment2.stream().filter(item2 -> {
                        return item2.get("rbc_pid").equals(entityComment.getRbc_id());
                    })
                    //.map(item2 -> {
                    //    //评论是否已点赞
                    //    boolean existsEntity = SvcRedbookData.getBean().existsEntity("comment", (String) item2.get("rbc_id"), getUid());
                    //    item2.put("is_good", existsEntity);
                    //    return item2;
                    //})
                    .collect(Collectors.toList());

            item.put("list_2", list2);
        }

        XReturn r = XReturn.getR(0);
        r.setData("list", list);

        return r;
    }

    /**
     * 2级评论列表
     */
    @GetMapping({"list2"})
    public XReturn commentList2() {
        InputData inputData = InputData.fromRequest();
        if (!inputData.existsKey("id")) {
            return XReturn.getR(20118, "miss id");
        }
        String id = inputData.input("id");

        RedbookComment entityCommentParent = SvcRedbookComment.getApp().getEntity(id);
        if (entityCommentParent == null) {
            return XReturn.getR(20124, "id 异常");
        }

        JoinWrapperPlus<RedbookComment> query = SvcRedbookComment.getBean().selectQuery(inputData);
        query.eq("rbc_pid", entityCommentParent.getRbc_id())
                .gt("rbc_reply_num", getCommentMaxNum())
                .eq("rbc_enable", 1);
        query.orderByAsc("rbc_create_date")
                .orderByAsc("rbc_id");

        IPage<RedbookComment> page = new Page<>(getPageIndex(), getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcRedbookComment.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();

        for (Map<String, Object> item : list) {
            RedbookComment entityComment = SvcRedbookComment.getApp().loadEntity(item);

            //是否点赞
            //boolean doGood = SvcRedbookData.getBean().existsEntity("comment", entityComment.getRbc_id(), getUid());
            //item.put("is_good", doGood);
        }

        XReturn r = XReturn.getR(0);
        r.setData("list", list);

        return r;
    }


    /**
     * 被评论列表
     */
    @GetMapping({"list_to"})
    public XReturn commentListTo() {
        InputData inputData = InputData.fromRequest();

        String[] select = {
                "rquan_id",
                "rquan_title",
                "rquan_url",
                "rbc_content",
                "user_id",
                "user_name",
                "user_headimg",
        };
        JoinWrapperPlus<RedbookComment> query = SvcRedbookComment.getBean().listQuery(inputData);
        query.join(RedbookQuan.table(), RedbookQuan.tableKey(), "rbc_rquan_id");
        query.join(SysUser.table(), SysUser.tableKey(), "rbc_uid");
        query.select(select);
        query.eq("rbc_pid", "")
                .eq("rbc_enable", 1)
                .eq("rquan_uid", getUid());
        query.orderByAsc("rbc_create_date")
                .orderByAsc("rbc_id");

        IPage<RedbookComment> page = new Page<>(getPageIndex(), getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcRedbookComment.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();

        for (Map<String, Object> item : list) {
        }

        XReturn r = XReturn.getR(0);
        r.setData("list", list);

        return r;
    }

    //删除
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/del")
    public XReturn del(@Validated @RequestBody VoRedbookCommentDel vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        RedbookComment entity = SvcRedbookComment.getApp().getEntity(vo.getId());
        if (entity == null) {
            return EnumSys.ERR_VAL.getR("评论ID异常");
        }
        if (!entity.getRbc_uid().equals(getUid())) {
            return XReturn.getR(20234, "非本人不能删除评论");
        }

        return SvcRedbookComment.getBean().delete(List.of(vo.getId()));
    }
}